//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.basic.action;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.UploadConfigBean;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.exception.BusinessException;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.config.MSProperties;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

@Api(
        tags = {"后端-基础接口"}
)
@Controller("ManageFileAction")
@RequestMapping({"${ms.manager.path}/file"})
public class ManageFileAction extends BaseFileAction {
    public ManageFileAction() {
    }

    @ApiOperation("处理post请求上传文件")
    @LogAnn(
            title = "处理post请求上传文件",
            businessType = BusinessTypeEnum.OTHER
    )
    @ApiImplicitParams({@ApiImplicitParam(
            name = "uploadPath",
            value = "上传文件夹地址",
            required = false,
            paramType = "form"
    ), @ApiImplicitParam(
            name = "file",
            value = "文件流",
            dataType = "__file",
            required = false,
            paramType = "form"
    ), @ApiImplicitParam(
            name = "rename",
            value = "是否重命名",
            required = false,
            paramType = "form",
            defaultValue = "true"
    ), @ApiImplicitParam(
            name = "appId",
            value = "上传路径是否需要拼接appId",
            required = false,
            paramType = "form",
            defaultValue = "false"
    ), @ApiImplicitParam(
            name = "uploadFolderPath",
            value = "是否修改上传目录",
            required = false,
            paramType = "form",
            defaultValue = "false"
    )})
    @PostMapping(
            value = {"/upload"},
            consumes = {"multipart/*"},
            headers = {"content-type=multipart/form-data"}
    )
    @ResponseBody
    public ResultData upload(@ApiIgnore UploadConfigBean bean, @ApiIgnore boolean uploadFolderPath, HttpServletRequest req, HttpServletResponse res) throws IOException {
        if (this.checkUploadPath(bean)) {
            return ResultData.build().error();
        } else {
            if (bean.isAppId()) {
                bean.setUploadPath(BasicUtil.getApp().getAppId() + File.separator + bean.getUploadPath());
            }

            UploadConfigBean config = new UploadConfigBean(bean.getUploadPath(), bean.getFile(), (String)null, uploadFolderPath, bean.isRename());
            return this.upload(config);
        }
    }

    @ApiOperation("处理post请求上传模板文件")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "uploadPath",
            value = "上传文件夹地址",
            required = false,
            paramType = "form"
    ), @ApiImplicitParam(
            name = "file",
            value = "文件流",
            dataType = "__file",
            required = false,
            paramType = "form"
    ), @ApiImplicitParam(
            name = "rename",
            value = "是否重命名",
            required = false,
            paramType = "form",
            defaultValue = "true"
    ), @ApiImplicitParam(
            name = "appId",
            value = "上传路径是否需要拼接appId",
            required = false,
            paramType = "form",
            defaultValue = "false"
    ), @ApiImplicitParam(
            name = "uploadFolderPath",
            value = "是否修改上传目录",
            required = false,
            paramType = "form",
            defaultValue = "false"
    )})
    @PostMapping({"/uploadTemplate"})
    @ResponseBody
    public ResultData uploadTemplate(@ApiIgnore UploadConfigBean bean, @ApiIgnore boolean uploadFolderPath, HttpServletResponse res) throws IOException {
        String uploadTemplatePath = MSProperties.upload.template;
        if (this.checkUploadPath(bean)) {
            return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("file.path")}));
        } else {
            if (StringUtils.isEmpty(bean.getUploadPath())) {
                bean.setUploadPath(uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId());
            } else if (!bean.getUploadPath().substring(0, uploadTemplatePath.length()).equalsIgnoreCase(uploadTemplatePath)) {
                throw new BusinessException("uploadPath参数错误");
            }

            UploadConfigBean config = new UploadConfigBean(bean.getUploadPath(), bean.getFile(), (String)null, uploadFolderPath, bean.isRename());
            ResultData resultData = this.uploadTemplate(config);
            if (!resultData.isSuccess()) {
                return ResultData.build().error(resultData.getMsg());
            } else {
                String templateUrl = uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId();
                if (!templateUrl.equals(bean.getUploadPath())) {
                    return ResultData.build().success();
                } else {
                    String fileUrl = (String)resultData.get("data");
                    if (fileUrl != null && (fileUrl.contains("../") || fileUrl.contains("..\\"))) {
                        return ResultData.build().error();
                    } else {
                        File zipFile = new File(BasicUtil.getRealTemplatePath(fileUrl));
                        ZipUtil.unzip(zipFile.getPath(), zipFile.getParent(), Charset.forName("gbk"));
                        FileUtil.del(zipFile);
                        String htmlPath = zipFile.getParent() + "/html";
                        if (FileUtil.exist(htmlPath)) {
                            FileUtil.del(htmlPath);
                        }

                        String dataPath = zipFile.getParent() + "/data";
                        if (FileUtil.exist(dataPath)) {
                            FileUtil.del(dataPath);
                        }

                        List<File> files = FileUtil.loopFiles(zipFile.getParent());
                        List<String> deniedList = (List)Arrays.stream(MSProperties.upload.denied.split(",")).map(String::toLowerCase).collect(Collectors.toList());
                        Iterator var14 = files.iterator();

                        while(var14.hasNext()) {
                            File file = (File)var14.next();
                            FileInputStream fileInputStream = new FileInputStream(file);
                            String fileType = FileTypeUtil.getType(file).toLowerCase();
                            if (deniedList.contains(fileType)) {
                                IOUtils.closeQuietly(fileInputStream);
                                FileUtil.del(zipFile.getParent());
                                throw new RuntimeException(StrUtil.format("压缩包内文件{}的类型{}禁止上传", new Object[]{file.getName(), fileType}));
                            }

                            IOUtils.closeQuietly(fileInputStream);
                        }

                        return ResultData.build().success();
                    }
                }
            }
        }
    }

    protected boolean checkUploadPath(UploadConfigBean bean) {
        return bean.getUploadPath() != null && (bean.getUploadPath().contains("../") || bean.getUploadPath().contains("..\\"));
    }
}
